package chapter17;

import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;

public class ListDemo extends JFrame{
	final int NUMBER_OF_FLAGS = 9;
	
	private String[] flagTitles = {"Canada", "China", "Denmark", "France", "Germany", "India", "Norway", "United Kingdom", "United States of America"};
	private JList jlst = new JList(flagTitles);
	private ImageIcon[] flagIcons = {
			new ImageIcon(ClassLoader.getSystemResource("chapter17/image/canada.jpg")),
			new ImageIcon(ClassLoader.getSystemResource("chapter17/image/china.jpg")),
			new ImageIcon(ClassLoader.getSystemResource("chapter17/image/denmark.jpg")),
			new ImageIcon(ClassLoader.getSystemResource("chapter17/image/france.jpg")),
			new ImageIcon(ClassLoader.getSystemResource("chapter17/image/germany.jpg")),
			new ImageIcon(ClassLoader.getSystemResource("chapter17/image/india.jpg")),
			new ImageIcon(ClassLoader.getSystemResource("chapter17/image/norway.jpg")),
			new ImageIcon(ClassLoader.getSystemResource("chapter17/image/uk.jpg")),
			new ImageIcon(ClassLoader.getSystemResource("chapter17/image/us.jpg"))
	};
	private JLabel[] jlbImageViewer = new JLabel[NUMBER_OF_FLAGS]; 

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ListDemo frame = new ListDemo();
		frame.setSize(600, 500);
		frame.setTitle("ListDemo");
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		
	}
	
	public ListDemo(){
		JPanel p = new JPanel(new GridLayout(3, 3, 5, 5));
		
		for (int i = 0; i < NUMBER_OF_FLAGS; i++) {
			p.add(jlbImageViewer[i] = new JLabel());
			jlbImageViewer[i].setHorizontalAlignment(SwingConstants.CENTER);
		}
		
		add(p, BorderLayout.CENTER);
		add(new JScrollPane(jlst), BorderLayout.WEST);
		
		jlst.addListSelectionListener(new ListSelectionListener(){
			public void valueChanged(ListSelectionEvent e){
				int[] indices = jlst.getSelectedIndices();
				int i;
				
				for (i = 0; i < indices.length; i++) {
					jlbImageViewer[i].setIcon(flagIcons[indices[i]]);
				}
				
				for (; i < NUMBER_OF_FLAGS; i++) {
					jlbImageViewer[i].setIcon(null);
					
				}
			}
		});
	}

}
